<?php if (! defined('APPPATH')) die('No direct script access allowed');
/**
 * RENARTI IK
 * An open source application development framework for PHP 5.2.0 or newer
 *
 * @package		RtiFramework
 * @author		Nauris Dambis <nauris.dambis@renarti.com>
 * @copyright	Copyright (c) 2012, RENARTI IK.
 * @license		http://renarti.com/#license
 * @link		http://renarti.com
 * @since		Version 1.0
 */

class RtiCookies
{
	protected $_encode;
	
	protected $_expire;
		
	/**
	 * Constructor
	 *
	 * Initialize the Cookies class and read configuration 
	 *
	 * @access	public
	 * @return	void
	 */
	public function __construct()
	{
		$this->_encode = Rti::config('config')->get('COOKIES_ENCODE');
		$this->_expire = Rti::config('config')->get('COOKIES_EXPIRE');		
	}
	
	/**
	 * Get Cookie value and if enabled data encoder then decode data
	 *
	 * @access	public
	 * @param	string $key
	 * @return	mixed
	 */
	function get($key)
	{
		if (! isset($_COOKIE[$key]))
		{
			return '';
		}
		
		$value = $_COOKIE[$key];
		
		if ($this->_encode === TRUE)
		{
			$value = Rti::encoder()->decode($value);
		}
		
		$value = unserialize($value);
		
		return $value;
		
	}
	
	/**
	 * 
	 * Set Cookie value and if enabled data encoder then encode data
	 * 
	 * @param string $key key The name of the cookie
	 * @param mixed $value The value of the cookie
	 * @param mixed $expire expire The time the cookie expires
	 * @param string $path cookies The path on the server in which the cookie will be available on
	 * @param mixed $domain The domain that the cookie is available to
	 * @param bool $secure Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client
	 * @param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
	 * @return	void
	 */
	public function set($key, $value, $expire = 0, $path = '/', $domain = NULL, $secure = FALSE, $httponly = FALSE) 
	{
		$this->delete($key);
		
		$expire = ($expire > 0)? time() + $expire : 0;
		
		$value = serialize($value);
		
		if ($this->_encode === TRUE)
		{
			$value = Rti::encoder()->encode($value);	
		}
		
		setcookie($key, $value, $expire, $path, $domain, $secure, $httponly);
	}
	
	/**
	 * 
	 * Delete Cookie by name
	 * 
	 * @param string $key key The name of the cookie
	 * @return	mixed
	 */
	public function delete($key, $path = '/')
	{
		setcookie($key, '', time() - 1, $path);
	}
	
}

/* End of file RtiCookies.php */
/* Location: ./system/core/RtiCookies.php */
